import api from '@/api'
import { defineStore } from 'pinia'
import { currentNodeInfo } from './currentNodeStore'
import { useEditorStore } from './editStore'
import router from '../router'
export const useUserStore = defineStore('user', {
  state: () => ({
    user: {
      id: '',
      name: '',
      account: '',
      role: 0,
      // password: '',
      token: '',
    },
    response: {},
  }),
  actions: {
    //用户登录
    async login(data: any) {
      await api.userInfo.userLogin(data).then((res: any) => {
        if (res.code === 200) {
          console.log("登录返回结果------》", res);
          this.user = res.data
          this.response = res
          console.log("当前用户角色------------------：",this.user.role);
          localStorage.setItem('satoken', res.data.token)
        }
      }).catch((error: any) => {
        console.log(error)
      })
    },
    //注册用户
    async register(data: any) {
      await api.userInfo.userRegister(data).then((res: any) => {
        if (res.code === 200) {
          console.log("注册返回结果------》", res);
          this.response = res
        }
      }).catch((error: any) => {
        console.log(error)
      })
    },
    //用户登出
    async logout(data: any) {
      const currentNodeStore = currentNodeInfo()
      const editorStore = useEditorStore()
       console.log("login out")
       if(currentNodeStore.isUpdate && this.user.role==0){
        // teacher update node ，auto save
         currentNodeStore.save()
       }else if(this.user.role == 1){
        //
        currentNodeStore.saveMark()
       }
      await api.userInfo.userLogout(data).then((res: any) => {
        if (res.code === 200) {

          console.log("登出返回结果------》", res);
          this.response = res
          localStorage.removeItem("satoken")
          //清空
          currentNodeStore.reset()
          //清除localstorage
           localStorage.removeItem("currentNodeStorage")

             router.push('/login')


        }
      }).catch((error: any) => {
        console.log(error)
      })
    },

  },
  persist: {
    enabled: true,
    strategies: [
      {
        storage: localStorage,
        paths: ['user'],
      },
    ],
  },
},
)

